const app = getApp();
import {
  post
} from '../../utils/request';
import {
  bMapTransqqMap,
  second2min,
  getDateFormat
} from '../../utils/util';

let itv;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showMchsModal: false,
    showItemsModal: false,
    itemsCurrent: 0,

    globalData: app.globalData,
    config: null,
    timeExpire: '00分00秒',
    detail: null,
    mchList: [],
    qrcode: null,
  },

  // 获取商家列表
  getMchList(type, id) {
    let location = wx.getStorageSync('location') || {};
    post(`/mch/info/list`, {
        ...location,
        inGoodsId: type === 0 ? id : 0,
        inServeId: type === 1 ? id : 0,
      })
      .then(resp => {
        if (resp.code === 0) {
          this.setData({
            mchList: resp.data,
          });
        }
      });
  },

  // 申请退款
  toRefund() {
    if (this.data.detail.validTime) {
      if (this.data.detail.validTime < getDateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss')) {
        wx.showToast({
          title: '订单已过期',
          icon: 'error'
        });
        return;
      }
    }
    wx.navigateTo({
      url: `/pages/order/refund?orderNo=${this.data.detail.orderNo}`,
    })
  },

  // 立即支付
  onPay() {
    wx.showLoading({
      title: '正在支付',
    });
    post(`/order/pay-by-no/${this.data.detail.orderNo}`)
      .then(res => {
        wx.hideLoading();
        if (res.code === 0) {
          wx.requestPayment({
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            success() {
              this.getDetail();
            },
            fail() {}
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'error'
          });
        }
      })
  },

  // 生成二维码
  genQrcode() {
    drawQrcode({
      width: 120,
      height: 120,
      canvasId: 'qrcode',
      text: this.data.detail.orderDetail.code,
    });
  },

  // 获取二维码
  getQrcode(code) {
    wx.showLoading({
      title: '正在加载',
    })
    post("/qrcode/unlimit", {
      scene: code,
      page: 'pages/order/verify',
      width: 120,
    }).then(res => {
      wx.hideLoading();
      if (res.code === 0) {
        this.setData({
          qrcode: 'data:image/png;base64,' + res.data.url
        });
      }
    });
  },

  // 获取订单详情
  getDetail() {
    if (itv) {
      clearInterval(itv);
    }

    let that = this;
    let {
      orderNo
    } = app.getPageOptions();
    if (!orderNo) {
      wx.showModal({
        title: '提示',
        content: '未找到订单编号',
      });
    }
    app.checkLogin(true, () => {
      post(`/order/detail/${orderNo}`).then(res => {
        if (res.code === 0) {
          let {
            data
          } = res;
          if (data.status === 0) {
            if (data.cancelStatus === 1) {
              data.status = -1; // 已取消
            } else if (data.expireStatus === 1) {
              data.status = -2; // 已超时
            }
          }
          // 待付款倒计时
          if (data.status === 0) {
            let second = Math.floor((new Date(data.timeExpire).getTime() - new Date().getTime()) / 1000);
            this.setData({
              timeExpire: second2min(second)
            });
            itv = setInterval(() => {
              if (second > 0) {
                this.setData({
                  timeExpire: second2min(second)
                });
                second--;
              } else {
                clearInterval(itv);
                that.getDetail();
              }
            }, 1000);
          }
          if (data.orderDetail.type === 0 || data.orderDetail.type === 1) {
            that.getMchList(data.orderDetail.type, data.orderDetail.pid);
          }

          that.setData({
            detail: data,
          });
          // 生成二维码
          if (data.status > 0 && (data.type === 1 || data.type === 2)) {
            // this.getQrcode(data.orderDetail.code);
          }
        }
        if (res.code === -1) {
          wx.showToast({
            title: res.msg,
          });
        }
      });
    });
  },

  // 联系商家
  onServiceTel(e) {
    let {
      servicetel
    } = e.currentTarget.dataset;
    if (servicetel) {
      wx.makePhoneCall({
        phoneNumber: servicetel,
      });
    }
  },

  // 商家导肮
  onAddress(e) {
    let {
      lng,
      lat,
      address
    } = e.currentTarget.dataset;
    let local = bMapTransqqMap(lng, lat);
    wx.openLocation({
      longitude: local.longitude,
      latitude: local.latitude,
      address: address,
    });
  },

  // 套餐权益模态框关闭
  closeItemsModal() {
    this.setData({
      showItemsModal: false,
      itemsCurrent: 0,
    });
  },

  // 套餐权益模态框打开
  openItemsModal(e) {
    let {
      idx
    } = e.currentTarget.dataset;
    this.setData({
      showItemsModal: true,
      itemsCurrent: idx,
    });
  },

  // 适用商家模态框关闭
  closeMchsModal() {
    this.setData({
      showMchsModal: false
    });
  },

  // 适用商家模态框打开
  openMchsModal() {
    this.setData({
      showMchsModal: true
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    app.setLocation();
    wx.setBackgroundColor({
      backgroundColor: "#f6f6f6"
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getDetail();

    app.getConfig(config => {
      this.setData({
        config
      });
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
});